package admin

import (
	"chaowan/data_source"
	"chaowan/models"
	"chaowan/service"
	"github.com/gin-gonic/gin"
	"net/http"
	"time"
)

type PushsRBody struct {
	Data       []models.Push `json:"data"`
	PageNo     int           `json:"pageNo"`
	PageSize   int           `json:"pageSize"`
	TotalCount int64         `json:"totalCount"`
	TotalPage  int64         `json:"totalPage"`
}

func Pushs(ctx *gin.Context) {
	request := OrderlistBody{}
	ctx.ShouldBind(&request)
	currentPage := request.Page
	pageSize := request.Pagesize
	offsetNum := pageSize * (currentPage - 1)
	var count int64
	var users []models.Push
	res := data_source.Db
	res.Model(&models.Push{}).Count(&count)
	res.Limit(pageSize).Offset(offsetNum).Order("id desc").Find(&users)

	var totalPage int64
	mo := count % int64(pageSize)
	if mo > 0 {
		totalPage = count/int64(pageSize) + 1
	} else {
		totalPage = count / int64(pageSize)
	}
	data := PushsRBody{
		Data:       users,
		PageNo:     currentPage,
		PageSize:   pageSize,
		TotalCount: count,
		TotalPage:  totalPage,
	}

	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    data,
		"msg":     "ok",
	})
	return

}

type PushaddBody struct {
	Title string `json:"title" gorm:"title"`
	Body  string `json:"body" gorm:"body"`
}

func Pushadd(ctx *gin.Context) {
	request := PushaddBody{}
	ctx.ShouldBind(&request)
	title := request.Title
	body := request.Body
	addpush := models.Push{
		Title:   title,
		Body:    body,
		Addtime: time.Now().Unix(),
	}
	data_source.Db.Create(&addpush)
	var user []models.User
	data_source.Db.Find(&user)
	var cids []string
	for _, u := range user {

		if u.Cid != "" {
			cids = append(cids, u.Cid)
		}

	}
	service.Getuixx(cids, title, body)
	ctx.JSON(http.StatusOK, gin.H{
		"code":    0,
		"error":   0,
		"success": 200,
		"data":    "ok",
		"msg":     "ok",
	})
	return

}
